import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getpagetitle from '@/utils/get-page-title'
import { asyncRoutes } from '@/router/index'
// 关闭进度条加载圈圈
NProgress.configure({ showSpinner: false }) // NProgress Configuration

router.beforeEach(async(to, from, next) => {
  const arr = ['/login', '/404']
  // 开启进度条
  NProgress.start()
  const token = store.state.user.token
  if (token) {
    if (to.path === '/login') {
      next('/')
      // 结束进度条
      NProgress.done()
    } else {
      if (!store.state.user.info.userId) {
        const res = await store.dispatch('user/getUserInfo')
        console.log(res)
        const newAsyncRoutes = asyncRoutes.filter((item) => {
          const menuName = item.children[0].name
          return res.includes(menuName)
        })
        console.log(newAsyncRoutes)
        newAsyncRoutes.push({ path: '*', redirect: '/404', hidden: true })
        // 动态添加路由
        router.addRoutes(newAsyncRoutes)
        // 存入动态路由到vuex
        store.commit('menu/getMenuList', newAsyncRoutes)
        next({
          ...to,
          replace: true
        })
      } else {
        next()
      }
    }
  } else {
    if (arr.includes(to.path)) {
      next()
    } else {
      next('/login')
      // 结束进度条
      NProgress.done()
      Message.warning('您还没登录，请先登录！')
    }
  }
})

router.beforeEach((to, from, next) => {
  // 切换组件时，动态设置标题
  document.title = getpagetitle(to.meta.title)
  next()
})
// 页面跳转结束的处理函数
router.afterEach((to, from) => {
  // 结束进度条
  NProgress.done()
})
